package com.baizhi.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baizhi.Service.UserService;
import com.baizhi.entity.User;
import com.baizhi.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author：请允悲
 * @Slogan：致敬大师，致敬未来的me
 * @Package：com.baizhi.controller
 * @Project：springbootjwt
 * @name：UserController
 * @Date：2023/9/20 16:35
 * @Filename：UserController
 */
@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/user/login")
    public Map<String,Object> login(User user)
    {
        log.info("用户名："+user.getUsername());
        log.info("密码："+user.getPassword());
        Map<String,Object> map=new HashMap<>();
//        User user1=new User();
//        user.setId(1);
//        user.setUsername("xiaochen");
//        user.setPassword("123");
        try {
             User userDB = userService.login(user);
            System.out.println(userDB);
            Map<String,String> payload=new HashMap<>();
            payload.put("id",userDB.getId().toString());
            payload.put("username",userDB.getUsername());
            //生成jwt的令牌
             String token = JWTUtils.getToken(payload);
            map.put("state",true);
            map.put("msg","认证成功");
            map.put("token",token);
        }
        catch (Exception ex)
        {

            map.put("state",false);
            map.put("msg", ex.getMessage());
//            User userDB = userService.login(user);
//            System.out.println(userDB);
        }

        return map;
    }


    @PostMapping("/user/test")
    public Map<String,String> vertyToken(HttpServletRequest request){
         HashMap<String, String> map = new HashMap<>();
         String token = request.getHeader("token");
         DecodedJWT verify = JWTUtils.verify(token);
         log.info("用户id:"+verify.getClaim("id").asString());
        log.info("用户name:"+verify.getClaim("username").asString());
        map.put("state","true");
        map.put("msg","请求成功");
        return map;
    }
}
